package me.ywd.eureka.client.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author Ye_Wenda
 * @Date 9/7/2017
 */
@RestController
@RequestMapping("spring")
public class ClientDemoController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private ObjectMapper objectMapper;

    @GetMapping("instances")
    public String instances() throws JsonProcessingException {
        List<String> serviceIds = discoveryClient.getServices();
        List<ServiceInstance> instances = new ArrayList<>();
        for(String serviceId : serviceIds) {
            instances.addAll(discoveryClient.getInstances(serviceId));

//            for (ServiceInstance instance : instances) {
//                msg += "ServiceId:" + instance.getServiceId() + ",  Host:" + instance.getHost() + ",  Port:" + instance.getPort() + ",  URI:" + instance.getUri() + ",  MetaData:" + instance.getMetadata();
//            }
        }
        return objectMapper.writeValueAsString(instances);
    }
}
